#include "Parser.h"
#include <string.h>
#include <sstream>

Parser::Parser(const std::string& fileName) :
    fileToRead(fileName.c_str())
{
    element = new TraceElement();
}

Parser::~Parser()
{
	if(element != 0)
	{
		delete element;
		element = 0;
	}
}

Parser::TraceElement* Parser::readNextElement()
{
    if(!fileToRead.good())
        return NULL;
    
    char line[200];
    fileToRead.getline(line, 200);
    
    char * pch = strtok(line," ,");
    if(pch == NULL)
        return NULL;

    if (strcmp(pch, "I") == 0)
        element->type = TraceType::I;
    
    else if (strcmp(pch, "L") == 0)
        element->type = TraceType::L;
    
    else if (strcmp(pch, "S") == 0)
        element->type = TraceType::S;
    
    else if (strcmp(pch, "M") == 0)
        element->type = TraceType::M;

	else if (strcmp(pch, "#") == 0)
		return readNextElement();
    
    pch = strtok(NULL," ,");
    if(pch == NULL)
        return NULL;
    std::stringstream ss;
    ss << std::hex << pch;
    ss >> element->adress;
    
    pch = strtok(NULL," ,");
    if(pch == NULL)
        return NULL;
    element->size = atoi(pch);
    
    return element;
}